<template>
  <view class="detail-container">
    <!-- 好友基本信息 -->
    <view class="friend-profile">
      <view class="avatar-section">
        <image 
          v-if="friendInfo.avatar" 
          :src="friendInfo.avatar" 
          class="friend-avatar"
          mode="aspectFill"
          @error="handleAvatarError"
        />
        <view v-else class="default-avatar">
          <text class="avatar-text">{{ friendInfo.name.charAt(0) }}</text>
        </view>
        <view :class="['online-status', friendInfo.isOnline ? 'online' : 'offline']"></view>
      </view>
      
      <view class="friend-basic-info">
        <text class="friend-name">{{ friendInfo.name }}</text>
        <text class="friend-id">ID: {{ friendInfo.id }}</text>
        <text class="friend-status">{{ friendInfo.isOnline ? '在线' : '离线' }}</text>
        <text class="last-seen">{{ formatLastSeen(friendInfo.lastSeen) }}</text>
      </view>
    </view>
    
    <!-- 好友统计信息 -->
    <view class="friend-stats">
      <view class="stat-item">
        <text class="stat-number">{{ friendInfo.gameCount || 0 }}</text>
        <text class="stat-label">游戏次数</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ friendInfo.friendDays || 0 }}</text>
        <text class="stat-label">好友天数</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ friendInfo.messageCount || 0 }}</text>
        <text class="stat-label">消息数</text>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn primary" @click="sendMessage">
        <text class="btn-icon">💬</text>
        <text class="btn-text">发消息</text>
      </button>
      <button class="action-btn secondary" @click="callFriend">
        <text class="btn-icon">📞</text>
        <text class="btn-text">语音通话</text>
      </button>
      <button class="action-btn secondary" @click="videoCall">
        <text class="btn-icon">📹</text>
        <text class="btn-text">视频通话</text>
      </button>
    </view>
    
    <!-- 好友信息详情 -->
    <view class="friend-details">
      <view class="detail-section">
        <view class="section-header">
          <text class="section-title">基本信息</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">昵称</text>
          <text class="detail-value">{{ friendInfo.name }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">用户ID</text>
          <text class="detail-value">{{ friendInfo.id }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">注册时间</text>
          <text class="detail-value">{{ formatDate(friendInfo.registerTime) }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">成为好友</text>
          <text class="detail-value">{{ formatDate(friendInfo.friendSince) }}</text>
        </view>
      </view>
      
      <view class="detail-section">
        <view class="section-header">
          <text class="section-title">个人资料</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">个性签名</text>
          <text class="detail-value">{{ friendInfo.signature || '这个人很懒，什么都没写' }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">兴趣爱好</text>
          <text class="detail-value">{{ friendInfo.hobbies || '未设置' }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">所在地</text>
          <text class="detail-value">{{ friendInfo.location || '未设置' }}</text>
        </view>
      </view>
      
      <view class="detail-section">
        <view class="section-header">
          <text class="section-title">游戏数据</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">生存游戏</text>
          <text class="detail-value">{{ friendInfo.gameLevel || '新手' }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">最高分</text>
          <text class="detail-value">{{ friendInfo.highScore || 0 }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">成就数量</text>
          <text class="detail-value">{{ friendInfo.achievements || 0 }}个</text>
        </view>
      </view>
    </view>
    
    <!-- 最近动态 -->
    <view class="recent-activities">
      <view class="section-header">
        <text class="section-title">最近动态</text>
        <text class="more-btn" @click="viewAllActivities">查看全部</text>
      </view>
      
      <view v-if="activities.length === 0" class="empty-activities">
        <text class="empty-text">暂无动态</text>
      </view>
      
      <view v-else class="activity-list">
        <view 
          v-for="activity in activities" 
          :key="activity.id"
          class="activity-item"
        >
          <view class="activity-icon">
            <text class="icon-text">{{ activity.icon }}</text>
          </view>
          <view class="activity-content">
            <text class="activity-title">{{ activity.title }}</text>
            <text class="activity-desc">{{ activity.description }}</text>
            <text class="activity-time">{{ formatTime(activity.time) }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="bottom-btn" @click="showMoreOptions">
        <text class="btn-icon">⋯</text>
        <text class="btn-text">更多</text>
      </button>
      <button class="bottom-btn" @click="deleteFriend">
        <text class="btn-icon">🗑️</text>
        <text class="btn-text">删除好友</text>
      </button>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import appStateManager from '@/utils/app-state-manager.js'

export default {
  data() {
    return {
      friendId: '',
      friendInfo: {
        id: '',
        name: '',
        avatar: '',
        isOnline: false,
        lastSeen: '',
        gameCount: 0,
        friendDays: 0,
        messageCount: 0,
        registerTime: '',
        friendSince: '',
        signature: '',
        hobbies: '',
        location: '',
        gameLevel: '',
        highScore: 0,
        achievements: 0
      },
      activities: [
        {
          id: 1,
          icon: '🎮',
          title: '完成生存游戏',
          description: '在生存游戏中获得了新纪录',
          time: new Date(Date.now() - 3600000).toISOString()
        },
        {
          id: 2,
          icon: '🏆',
          title: '获得成就',
          description: '解锁了"生存专家"成就',
          time: new Date(Date.now() - 7200000).toISOString()
        }
      ]
    }
  },
  
  onLoad(options) {
    console.log('好友详情页面接收参数:', options)
    if (options.id) {
      this.friendId = options.id
      console.log('设置friendId:', this.friendId)
      this.loadFriendInfo()
    } else {
      console.error('未接收到好友ID参数')
      uni.showToast({
        title: '参数错误',
        icon: 'error'
      })
    }
  },
  
  methods: {
    async loadFriendInfo() {
      try {
        // 强制刷新服务器状态
        console.log('强制刷新服务器状态...')
        await apiService.refreshServerStatus()
        const serverStatus = appStateManager.getState('server')
        console.log('当前服务器状态:', serverStatus.isOnline ? '在线' : '离线')
        
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          uni.showModal({
            title: '用户未登录',
            content: '请先登录',
            showCancel: false
          })
          return
        }

        const userData = JSON.parse(currentUser)
        
        // 如果用户数据中没有ID，尝试通过邮箱获取
        if (!userData.id && userData.email) {
          try {
            const userId = await apiService.getUserId(userData)
            if (userId) {
              userData.id = userId
              // 更新本地存储
              uni.setStorageSync('currentUser', JSON.stringify(userData))
            }
          } catch (error) {
            console.log('获取用户ID失败:', error)
          }
        }
        
        if (!userData.id) {
          uni.showToast({
            title: '用户信息不完整',
            icon: 'error'
          })
          return
        }
        
        // 直接根据ID获取用户信息
        console.log('根据ID获取用户信息...', this.friendId)
        const userResponse = await apiService.getUserById(this.friendId)
        
        if (userResponse.code === 'SUCCESS' && userResponse.data) {
          const user = userResponse.data
          this.friendInfo = {
            id: user.id,
            name: user.name,
            email: user.email,
            avatar: user.avatar,
            isOnline: false,
            lastSeen: user.last_login || '',
            gameCount: user.game_count || 0,
            friendDays: user.friend_days || 0,
            messageCount: user.message_count || 0,
            registerTime: user.created_at || '',
            friendSince: user.friend_since || '',
            signature: user.signature || '',
            hobbies: user.hobbies || '',
            location: user.location || '',
            gameLevel: user.game_level || '',
            highScore: user.high_score || 0,
            achievements: user.achievements || 0
          }
          console.log('成功加载用户信息:', this.friendInfo)
        } else {
          uni.showToast({
            title: '用户不存在',
            icon: 'error'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        console.error('加载好友信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      }
    },
    
    sendMessage() {
      uni.showToast({
        title: `给${this.friendInfo.name}发消息`,
        icon: 'none'
      })
      // 这里可以跳转到聊天页面
    },
    
    callFriend() {
      uni.showToast({
        title: '语音通话功能开发中',
        icon: 'none'
      })
    },
    
    videoCall() {
      uni.showToast({
        title: '视频通话功能开发中',
        icon: 'none'
      })
    },
    
    viewAllActivities() {
      uni.showToast({
        title: '查看全部动态',
        icon: 'none'
      })
    },
    
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['设置备注', '加入黑名单', '举报用户', '查看朋友圈'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.setRemark()
              break
            case 1:
              this.addToBlacklist()
              break
            case 2:
              this.reportUser()
              break
            case 3:
              this.viewMoments()
              break
          }
        }
      })
    },
    
    setRemark() {
      uni.showModal({
        title: '设置备注',
        editable: true,
        placeholderText: '请输入备注名称',
        success: (res) => {
          if (res.confirm && res.content) {
            this.friendInfo.name = res.content
            uni.showToast({
              title: '备注已设置',
              icon: 'success'
            })
          }
        }
      })
    },
    
    addToBlacklist() {
      uni.showModal({
        title: '加入黑名单',
        content: `确定要将"${this.friendInfo.name}"加入黑名单吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '已加入黑名单',
              icon: 'success'
            })
          }
        }
      })
    },
    
    reportUser() {
      uni.showModal({
        title: '举报用户',
        content: `确定要举报"${this.friendInfo.name}"吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '举报已提交',
              icon: 'success'
            })
          }
        }
      })
    },
    
    viewMoments() {
      uni.showToast({
        title: '朋友圈功能开发中',
        icon: 'none'
      })
    },
    
    deleteFriend() {
      uni.showModal({
        title: '删除好友',
        content: `确定要删除好友"${this.friendInfo.name}"吗？删除后将无法恢复。`,
        success: (res) => {
          if (res.confirm) {
            this.confirmDeleteFriend()
          }
        }
      })
    },
    
    async confirmDeleteFriend() {
      try {
        const currentUserStr = uni.getStorageSync('currentUser')
        if (!currentUserStr) {
          uni.showToast({ title: '用户未登录', icon: 'error' })
          return
        }
        const currentUser = JSON.parse(currentUserStr)

        const response = await apiService.deleteFriend(currentUser.id, parseInt(this.friendId))
        if (response.code === 'SUCCESS') {
          uni.showToast({ title: '已删除好友', icon: 'success' })
          setTimeout(() => { uni.navigateBack() }, 1200)
        } else {
          throw new Error('服务器返回失败')
        }
      } catch (error) {
        console.error('删除好友失败:', error)
        uni.showToast({ title: '删除失败', icon: 'error' })
      }
    },
    
    handleAvatarError() {
      console.log('头像加载失败')
    },
    
    formatLastSeen(lastSeen) {
      if (!lastSeen) return '从未'
      
      const now = new Date()
      const lastSeenDate = new Date(lastSeen)
      const diff = now - lastSeenDate
      
      if (diff < 60000) { // 1分钟内
        return '刚刚在线'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前在线`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前在线`
      } else {
        return lastSeenDate.toLocaleDateString()
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      return new Date(dateString).toLocaleDateString()
    },
    
    formatTime(timeString) {
      const now = new Date()
      const targetTime = new Date(timeString)
      const diff = now - targetTime
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return targetTime.toLocaleDateString()
      }
    }
  }
}
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
  padding-bottom: 120rpx;
}

/* 好友基本信息 */
.friend-profile {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  text-align: center;
}

.avatar-section {
  position: relative;
  display: inline-block;
  margin-bottom: 20rpx;
}

.friend-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid #fff;
}

.default-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4rpx solid #fff;
}

.avatar-text {
  color: white;
  font-size: 48rpx;
  font-weight: bold;
}

.online-status {
  position: absolute;
  bottom: 8rpx;
  right: 8rpx;
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  border: 4rpx solid #fff;
}

.online-status.online {
  background: #4CAF50;
}

.online-status.offline {
  background: #ccc;
}

.friend-basic-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.friend-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.friend-id {
  font-size: 24rpx;
  color: #666;
}

.friend-status {
  font-size: 24rpx;
  color: #4CAF50;
}

.last-seen {
  font-size: 22rpx;
  color: #999;
}

/* 统计信息 */
.friend-stats {
  display: flex;
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 8rpx;
}

.stat-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: white;
  border: none;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
}

.action-btn.primary {
  background: #667eea;
  color: white;
}

.btn-icon {
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.btn-text {
  font-size: 22rpx;
  font-weight: 500;
}

/* 详情信息 */
.friend-details {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.detail-section {
  margin-bottom: 30rpx;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 12rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.more-btn {
  font-size: 22rpx;
  color: #667eea;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 26rpx;
  color: #666;
  min-width: 120rpx;
}

.detail-value {
  font-size: 26rpx;
  color: #333;
  text-align: right;
  flex: 1;
}

/* 最近动态 */
.recent-activities {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.empty-activities {
  text-align: center;
  padding: 40rpx;
}

.empty-text {
  font-size: 24rpx;
  color: #999;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.activity-icon {
  margin-right: 20rpx;
}

.icon-text {
  font-size: 32rpx;
}

.activity-content {
  flex: 1;
}

.activity-title {
  display: block;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.activity-desc {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.activity-time {
  display: block;
  font-size: 20rpx;
  color: #999;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background: white;
  padding: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.bottom-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border: none;
  padding: 16rpx;
  margin: 0 10rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.bottom-btn:active {
  background: #f0f0f0;
}

.bottom-btn .btn-icon {
  font-size: 28rpx;
  margin-bottom: 4rpx;
}

.bottom-btn .btn-text {
  font-size: 20rpx;
  color: #666;
}
</style>
